import './pSum.less'

import { Area } from '@antv/g2plot'
import { Empty, Progress, Table } from 'antd'
import type { ColumnsType } from 'antd/lib/table'
import { useEffect, useRef, useState } from 'react'

import { paddingZero } from '@/utils/tool'

import styles from './productionRank.module.less'

const idMap = {
  iron: 'total-iron',
  pack: 'total-pack',
  check: 'total-check'
}
const averageMap = {
  iron: 'average-iron',
  pack: 'average-pack',
  check: 'average-check'
}
export default (props) => {
  const { isFull, data, field } = props
  const yieldTable = useRef<any>()

  const timer = useRef<any>()

  const [scrollY, setSCrollY] = useState<number>(0)
  const [yieldColumns, setYieldColumns] = useState<any[]>([])
  const [yieldData, setYieldData] = useState<any[]>([])
  const [productionTotalNum, setProductionTotalNum] = useState<number | string>(
    0
  )
  const [productionCapitalNum, setProductionCapitalNum] = useState<
    number | string
  >(0)

  const [area1, setArea1] = useState<any>()
  const [area2, setArea2] = useState<any>()

  // 总产量趋势
  useEffect(() => {
    const area = new Area(`total-${field}`, {
      data: [],
      xField: 'x',
      yField: 'y',
      smooth: true,
      autoFit: true,
      areaStyle: {
        fill: 'l(270) 0:#000C6D 1:#0EC4DE'
      },
      line: {
        color: '#0EC4DE'
      },
      xAxis: {
        range: [0.02, 0.98],
        label: null,
        grid: null,
        line: null
      },
      yAxis: {
        range: [0.02, 0.98],
        label: null,
        grid: null
      }
    })
    area.render()
    setArea1(area)
  }, [])

  // 人均产量趋势
  useEffect(() => {
    const area = new Area(`average-${field}`, {
      data: [],
      xField: 'x',
      yField: 'y',
      smooth: true,
      autoFit: true,
      areaStyle: {
        fill: 'l(270) 0:#000C6D 1:#F7B500'
      },
      line: {
        color: '#F7B500'
      },
      xAxis: {
        range: [0.02, 0.98],
        label: null,
        grid: null,
        line: null
      },
      yAxis: {
        range: [0.02, 0.98],
        label: null,
        grid: null
      }
    })
    area.render()
    setArea2(area)
  }, [])

  useEffect(() => {
    if (data && data.productionTotal && data.productionTotal.length) {
      const { productionTotal } = data
      setProductionTotalNum(productionTotal[productionTotal.length - 1].y)
      const newArray = []
      for (let i = 1; i <= 24; i++) {
        let date
        // {x: '1 3'}
        const current = productionTotal.find((item) => {
          const a = item.x.split(' ')
          date = a[0]
          const time = a[1]
          return i === Number(time)
        })
        if (current) {
          newArray.push(current)
        } else {
          newArray.push({ x: `${date}  ${paddingZero(i)}`, y: 0 })
        }
      }

      area1.update({
        data: newArray
      })
    }
  }, [area1, data])

  useEffect(() => {
    if (data && data.productionCapital && data.productionCapital.length) {
      const { productionCapital } = data
      setProductionCapitalNum(productionCapital[productionCapital.length - 1].y)
      const newArray = []
      for (let i = 1; i <= 24; i++) {
        let date
        const current = productionCapital.find((item) => {
          const a = item.x.split(' ')
          date = a[0]
          const time = a[1]
          return i === Number(time)
        })
        if (current) {
          newArray.push(current)
        } else {
          newArray.push({ x: `${date}  ${paddingZero(i)}`, y: 0 })
        }
      }
      console.log(newArray, 'newArray')

      area2.update({
        data: newArray
      })
    }
  }, [area2, data])

  // 产量数据
  useEffect(() => {
    if (data && data.rankList && data.rankList.length) {
      const total = data.rankList.find((list) => list.ranking == 1) || {}
      const columns: ColumnsType<any[]> = [
        {
          title: '排名',
          dataIndex: 'ranking',
          key: 'ranking',
          align: 'center'
        },
        {
          title: '产量',
          dataIndex: 'production',
          key: 'production',
          align: 'center',
          render: (value) => {
            const percent = Math.floor((value / total.production) * 100)
            const color = () => {
              if (percent <= 25) {
                return 'yellow'
              }
              if (percent <= 75 && percent > 25) {
                return 'green'
              }
              if (percent <= 90 && percent >= 75) {
                return 'blue'
              }
              if (percent < 100 && percent > 90) {
                return '#44D7B6'
              }
              if (percent === 100) {
                return 'red'
              }
              return 'black'
            }
            return (
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <Progress
                  strokeColor={color()}
                  showInfo={false}
                  percent={percent}
                  trailColor="#072C88"
                />
                <span>{value}</span>
              </div>
            )
          }
        },
        {
          title: '员工编号',
          dataIndex: 'workNo',
          key: 'workNo',
          align: 'center'
        },
        {
          title: '员工姓名',
          dataIndex: 'realName',
          key: 'realName',
          align: 'center'
        }
      ]
      setYieldColumns(columns)
      setYieldData([...data.rankList])
    }
  }, [data])

  // 产量表格滚动
  useEffect(() => {
    if (yieldTable && yieldTable.current && yieldData && yieldData.length) {
      const target = yieldTable.current.getElementsByClassName('ant-table-body')

      clearInterval(timer.current)

      const t = setInterval(() => {
        target[0].scrollTop += 1

        if (
          ++target[0].scrollTop >=
          target[0].scrollHeight - target[0].clientHeight
        ) {
          target[0].scrollTop = 0
        }
      }, 64)

      timer.current = t
    }
  }, [yieldTable, yieldData, scrollY])

  useEffect(() => {
    if (!yieldData || !yieldData.length) return
    setTimeout(() => {
      const tableHeight = yieldTable.current.clientHeight
      const headHeight =
        yieldTable.current.getElementsByClassName('ant-table-thead')?.[0]
          ?.clientHeight
      setSCrollY(tableHeight - headHeight - 8)
    }, 200)
  }, [yieldTable, yieldData])

  return (
    <div className={styles.container} id="pTable">
      <header className={styles.rankHeader}>产量排名</header>
      <div className={styles.outBox}>
        <div className={styles.areaBox}>
          <div className={styles.area}>
            <div>总产量趋势</div>
            <div className={styles.totalCount}>{productionTotalNum}</div>
            <div id={idMap[field]} className={styles.areaMapBox} />
            {/* {field === 'iron' && (
              <div id="total-iron" className={styles.areaMapBox} />
            )}
            {field === 'pack' && (
              <div id="total-pack" className={styles.areaMapBox} />
            )}
            {field === 'check' && (
              <div id="total-check" className={styles.areaMapBox} />
            )} */}
          </div>
          <div className={styles.area}>
            <div>人均产量趋势</div>
            <div className={styles.averageCount}>{productionCapitalNum}</div>
            <div id={averageMap[field]} className={styles.areaMapBox} />
            {/* {field === 'iron' && (
              <div id="average-iron" className={styles.areaMapBox} />
            )}
            {field === 'pack' && (
              <div id="average-pack" className={styles.areaMapBox} />
            )}
            {field === 'check' && (
              <div id="average-check" className={styles.areaMapBox} />
            )} */}
          </div>
        </div>
        {yieldData && yieldData.length ? (
          <Table
            ref={yieldTable}
            className={styles.rankTable}
            pagination={false}
            rowKey={'ranking'}
            columns={yieldColumns}
            dataSource={yieldData}
            size={'middle'}
            scroll={{
              y: scrollY
            }}
          />
        ) : (
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            style={{ color: '#fff', height: '40%' }}
            className={styles.emptyImg}
          />
        )}
      </div>
    </div>
  )
}
